﻿using Microsoft.EntityFrameworkCore;
using Pipelines.Sockets.Unofficial.Buffers;
using Windows.FileStorage.Contract;
using Windows.FileStorage.Domain;
using Windows.FileStorage.Infrastructure.EFCore;
using Windows.Infrastructure.Share.Extensions;
using Windows.SeedWord;

namespace Windows.FileStorage.GrpcService
{
    public class AttachmentGrpcService : IAttachmentGrpcService
    {
        private readonly FileStorageDbContext _db;
        public AttachmentGrpcService( FileStorageDbContext db)
        {
            _db = db;
        }
        public async Task<AttachmentResponse> GetAttachment(AttachmentRequest request)
        {
            var query = _db.Attachment.AsQueryable();
            if (request.AttachmentId != null)
                query = query.Where(x => x.Id == request.AttachmentId);
            if (request.OwnerId != null)
                query = query.Where(x => x.OwnerId == request.OwnerId);
            var model = await query.FirstOrDefaultAsync();
            AttachmentResponse attachment = new();
            if (model != null)
            {
                attachment.OwnerId = model.OwnerId;
                attachment.AttachmentPath = "http://localhost:8888/" + model.SavePath;
            }
                
            return attachment;
        }
        public async Task SaveAttachment(AttachmentRequest request)
        {
            var model = await _db.Attachment.Where(x => x.OwnerId == request.OwnerId).FirstOrDefaultAsync();
            if (model != null)
            {
                _db.Attachment.Remove(model);
            }
            Attachment attachment = await _db.Attachment.FindByIdAsync(request.AttachmentId.Value);
            attachment.OwnerId = request.OwnerId;
            await _db.SaveChangesAsync();
        }
        public async Task<List<GetAttachmentsByOwnerIdsResponse>> GetAttachmentsByOwnerIds(GetAttachmentsByOwnerIdsRequest request)
        {
            var list = await _db.Attachment.Where(x => request.OwnerIds.Contains(x.OwnerId.Value)).ToListAsync();

            List<GetAttachmentsByOwnerIdsResponse> responses = new();
            foreach (var l in list)
            {
                GetAttachmentsByOwnerIdsResponse response = new()
                {
                    OwnerId = l.OwnerId.Value,
                    AttachmentPath = "http://localhost:8888/" + l.SavePath
                };
                responses.Add(response);
            }
            return responses;
        }
    }
}
